// plugin.js - https://postcss.org/docs/writing-a-postcss-plugin

// https://www.jianshu.com/p/21f792163247

const darkThemeSelector = 'html[data-theme="dark"]';

function ruleCreate(selector, list = [], postcss) {
  const rule = postcss.rule({
    selector: selector,
    raws: { before: "\n  ", between: " ", semicolon: true, after: "\n  " },
  });

  for (const item of list) {
    rule.append({
      prop: item.prop,
      value: item.value,
    });
  }

  return rule;
}

module.exports = (options = {}) => {
  return {
    postcssPlugin: "postcss-media", // 插件名字，以 postcss- 开头
    Once(root, postcss) {
      console.log("length ====>", root.nodes.length);

      // 此处 root 即为转换后的 AST，此方法转换一次 css 将调用一次

      // 判断 PostCSS 工作流程中，是否使用了某些 plugins
      const hasPlugin = (name) =>
        name.replace(/^postcss-/, "") === options.nestingPlugin ||
        postcss.result.processor.plugins.some(
          (pl) => pl.postcssPlugin === name
        );
      // 获取最终 CSS 值
      const getValue = (value, theme) => {
        return value.replace(reGroup, (match, group) => {
          return resolveColor(options, theme, group, match);
        });
      };

      root.append(
        ruleCreate(
          ".router-size",
          [
            {
              prop: "color",
              value: "#ff0000",
            },
            {
              prop: "font-size",
              value: "18px",
            },
          ],
          postcss
        )
      );

      root.append(
        ruleCreate(
          "html",
          [
            {
              prop: "--bgPlColor",
              value: "brown",
            },
            {
              prop: "--bgPhColor",
              value: "chocolate",
            },
          ],
          postcss
        )
      );

      // 遍历CSS声明
      // root.walkDecls((decl) => {
      //   if (decl.value !== "dark") return;

      //   const darkDecl = decl.clone({ value: "#ff0000" });
      //   console.log(decl.parent.selector);
      //   console.log(decl.prop, decl.value);
      //   console.log("====== walk =======");

      //   if (hasPlugin("postcss-nested")) {
      //     darkRule = postcss.rule({
      //       selector: `${darkThemeSelector} &`,
      //     });

      //     // 添加 dark 样式到目标 HTML 节点中
      //     if (darkRule) {
      //       darkRule.append(darkDecl);
      //       decl.after(darkRule);
      //       // root.append(darkRule);
      //       // decl.after("color: black");
      //     }
      //     decl.replaceWith(decl.clone({ value: "#ff0000" }));
      //   }
      // });

      root.walkRules((rule) => {
        console.log(rule.selector);

        let darkRule = null;
        let todo = [];
        todo._update_ = false;

        rule.walkDecls((decl) => {
          if (decl.value !== "dark") {
            return;
          } else {
            todo._update_ = true;
            todo.push(decl);
            const value = { value: "#ff0000" };
            decl.replaceWith(decl.clone(value));
          }
        });

        if (todo._update_) {
          if (hasPlugin("postcss-nested")) {
            darkRule = postcss.rule({
              selector: `${darkThemeSelector} ${rule.selector}`,
              raws: {
                before: "\n  ",
                between: " ",
                semicolon: true,
                after: "\n  ",
              },
            });
            // 添加 dark 样式到目标 HTML 节点中
            if (darkRule) {
              for (const el of todo) {
                darkRule.append(
                  el.clone({
                    value: "#0000ff",
                  })
                );
              }
              root.append(darkRule);
            }
          }
        }
      });
    },
    Rule(rule) {
      // console.log(rule.selector, rule.raws);
      // const label = "router-size";
      // if (rule.selector.includes(label)) {
      //   rule.append({
      //     prop: "font-size",
      //     value: "18px",
      //   });
      // }
      // console.log(rule.selector);
    },
    Declaration(decl, postcss) {
      // postcss 遍历 css 样式时调用，在这里可以快速获得 type 为 decl 的节点 (请参考第二节的 AST 对象)
      if (decl.value === "#ffffff") {
        decl.value = "white";
      }
      // console.log(decl.toString());
      // console.log(decl.parent.selector, decl.prop, decl.value);
    },
    // Declaration: {
    //   color(decl, postcss) {
    //     // 可以进一步获得 decl 节点指定的属性值，这里是获得属性为 color 的值
    //   },
    // },
    Comment(comment, postcss) {
      // 可以快速访问 AST 注释节点（type 为 comment）
      // comment.remove();
      comment.text = "可以快速访问 AST 注释节点";
    },
    AtRule(atRule, postcss) {
      // 可以快速访问 css 如 @media，@import 等 @定义的节点（type 为 atRule）
      console.log("=======>", atRule.name, atRule.type);
    },
  };
};
module.exports.postcss = true;
